package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.utils.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
public class UploadController {

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    @PostMapping("/upload")
    public Result upload(MultipartFile file){
        log.info("文件上传：{}",file.getOriginalFilename());
        //上传oss上
        try {
            String url = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());
            //返回的地址
            return Result.success(url);
        } catch (Exception e) {
            log.error("上传文件失败",e);
            return Result.error("上传文件失败");
        }
    }

    /*@PostMapping("/upload")
    public Result upload(MultipartFile file,String username,Integer age){
        // 获取文件后缀名, 上传过来的文件的名称, 154座位表.png
        String filename = file.getOriginalFilename();
        log.info("文件上传：{},{},{}",filename,username,age);
        // 生成唯一文件名 uuid.jpg
        String uuid = UUID.randomUUID().toString();
        // 154座位表.png, .png
        String extension = filename.substring(filename.lastIndexOf("."));
        String newFilename = uuid + extension;
        // 保存到d:/upload/目录下
        // 如果目录不存在，则创建目录
        String path = "d:/upload/";
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }
        try {
            //保存文件到 这个path目录下的这个文件newFilename
            file.transferTo(new File(path, newFilename));
        } catch (IOException e) {
            //error记录异常信息
            log.error("上传文件失败",e);
            return Result.error("上传文件失败");
        }
        return Result.success();
    }

    public static void main(String[] args) {
        String uuid = UUID.randomUUID().toString();
        System.out.println("uuid = " + uuid);
        String filename = "154座位表.png";
        String extension = filename.substring(filename.lastIndexOf("."));//png
        System.out.println("extension = " + extension);
        String newFilename = uuid + extension;
        System.out.println("newFilename = " + newFilename);
    }*/
}
